package cn.pfund;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import cn.pfund.entity.Admin;
import cn.pfund.entity.Permission;
import cn.pfund.service.AdminService;

/**
 * @description 权限认证
 * @author zhaominglei qq:351024274，专注于网站、app和游戏开发。
 * @date 2014年10月6日
 */
public class AuthenticationRealm extends AuthorizingRealm{

	@Resource(name="adminService")
	private AdminService adminService;

	/**
	 * 授权信息
	 * @param principals
	 *            principals
	 * @return 授权信息
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		String username = (String) super.getAvailablePrincipal(principals);
		List<String> permissions = new ArrayList<String>();
			Admin admin = new Admin();
			admin.setUsername(username);
			Set<Permission> pSet = adminService.getPermissions(admin);
			if (pSet != null && pSet.size() > 0) {
				for (Permission permission : pSet) {
					permissions.add(permission.getPermission());
				}
			}
        authorizationInfo.addStringPermissions(permissions); 
		return authorizationInfo;
		
	}

	/**
	 *  认证信息
	 *  认证回调函数,登录时调用
     * @param token
	 *            令牌
	 * @return 认证信息
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		Admin admin = adminService.getAdminByUsername(token.getUsername());
		if (admin != null) {
			if (!admin.getIsEnabled()) {
				throw new DisabledAccountException();
			}
			return new SimpleAuthenticationInfo(admin.getUsername(), admin.getPassword(), admin.getName());
		} else {
			return null;
		}
	}
}

